<template>
  <Navbar></Navbar>
  <n-card class="user-profile-card" style="margin-top: 88px">
    <div class="header">
      <div class="avatar-section">
        <n-avatar size="huge" :src="userInfo.userAvatar" @click="showAvatarModal" />
        <n-button size="small" class="edit-avatar-btn" @click="editAvatar">修改头像</n-button>
      </div>
      <n-button size="small" type="default" @click="goBack">返回</n-button>
    </div>
    <n-modal v-model:show="avatarModalVisible" preset="dialog" :style="{ width: '400px' }">
      <img :src="userInfo.userAvatar" class="large-avatar" />
    </n-modal>
    <n-divider>个人信息</n-divider>
    <n-form :model="userInfo" label-width="100px">
      <n-form-item label="用户ID">
        <n-input v-model:value="userInfo.id" disabled />
      </n-form-item>
      <n-form-item label="用户账号">
        <n-input v-model:value="userInfo.userAccount" disabled />
      </n-form-item>
      <n-form-item label="用户昵称">
        <n-input v-model:value="userInfo.userName" :disabled="!isEditing" />
      </n-form-item>
      <n-form-item label="用户简介">
        <n-input v-model:value="userInfo.userProfile" :disabled="!isEditing" />
      </n-form-item>
      <n-form-item label="注册时间">
        <n-input v-model:value="userInfo.createTime" disabled />
      </n-form-item>
      <n-form-item>
        <n-button @click="toggleEdit" type="primary">{{ isEditing ? '保存' : '编辑' }}</n-button>
        <n-button v-if="isEditing" @click="cancelEdit">取消</n-button>
      </n-form-item>
    </n-form>
  </n-card>
  <!-- 上面的代码保持不变 -->
  <input type="file" ref="fileInput" @change="handleFileChange" style="display: none;" />
</template>

<script lang="ts">
import { defineComponent, ref, reactive } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { useRouter } from 'vue-router'
import { NCard, NForm, NFormItem, NInput, NButton, NAvatar, NDivider, NModal, useMessage } from 'naive-ui'
import apiClient from '@/api/axios'
import Navbar from '@/components/Navbar.vue'

export default defineComponent({
  components: { Navbar },
  setup() {
    const authStore = useAuthStore()
    const router = useRouter()
    const user = authStore.state.user
    const message = useMessage()
    //为了防止页面刷新或服务器重启导致状态丢失，加载页面的时候从localStorage里面读取状态存进去
    if(!authStore.checkLogin()){
      router.push("/user/login")
    }

    //以下的值实际上是不一致的；Pinia 使用 reactive 创建的 state 对象是响应式的，当你直接将 user 对象赋值给一个变量时，它可能不是响应式的副本，因此在数据变化时不会自动更新。
    console.log("user =======================>" + JSON.stringify(user))
    console.log("authStore.state.user =======================>" + JSON.stringify(authStore.state.user))
    console.log("isLogin =======================>" + authStore.checkLogin())
    console.log("user =======================>" + JSON.stringify(user))


    const userInfo = reactive(authStore.state.user)

    const isEditing = ref(false)
    const originalUserInfo = ref({})
    const avatarModalVisible = ref(false)
    const fileInput = ref<HTMLInputElement | null>(null)

    // const fetchUserInfo = () => {
    //   const user = authStore.state.user
    //   if (user) {
    //     userInfo.id = user.id
    //     userInfo.userAccount = user.userAccount
    //     userInfo.userName = user.userName
    //     userInfo.userAvatar = user.userAvatar
    //     userInfo.userProfile = user.userProfile
    //     userInfo.createTime = user.createTime
    //     originalUserInfo.value = { ...userInfo }
    //   }
    // }


    /**
     * 重新发送登录用户信息请求，更新本地用户信息缓存
     */
    const updateLocalStorageUserInfo = async function() {
      const response = await apiClient.get("/user/getLoginUser")//这Store里拉取用户最信息的不去走请求后端一直走缓存搞这么久,这里直接在这重新请求后端解决
      const loginUser = response.data.data
      console.log("我怀疑这是有缓存:" + JSON.stringify(loginUser))
      localStorage.setItem("user", JSON.stringify(loginUser))
      console.log("再读读看" + localStorage.getItem("user"))
      authStore.state.user = loginUser
    }


    const toggleEdit = async () => {
      if (isEditing.value) {
        // 保存逻辑
        console.log('保存用户信息:', userInfo)
        try {
          await apiClient.post('/user/update/my', {
            userName: userInfo.userName,
            userProfile: userInfo.userProfile
          })
          updateLocalStorageUserInfo() // 更新本地存储的用户信息
          message.success('用户信息更新成功')
        } catch (error) {
          console.error('更新用户信息失败', error)
          message.error('更新用户信息失败')
        }
      }
      isEditing.value = !isEditing.value
    }

    const cancelEdit = () => {
      Object.assign(userInfo, originalUserInfo.value)
      isEditing.value = false
    }

    const editAvatar = () => {
      fileInput.value?.click()
    }

    const handleFileChange = async (event: Event) => {
      const target = event.target as HTMLInputElement
      const file = target.files?.[0]
      if (file) {
        const formData = new FormData()
        formData.append('file', file)
        try {
          const response = await apiClient.post('/upload/avatar', formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          })
          userInfo.userAvatar = response.data.url
          message.success('头像上传成功')
        } catch (error) {
          console.error('上传头像失败', error)
          message.error('上传头像失败')
        }
      }
    }

    const showAvatarModal = () => {
      avatarModalVisible.value = true
    }

    const goBack = () => {
      router.back()
    }

    // fetchUserInfo()

    return {
      userInfo,
      isEditing,
      toggleEdit,
      cancelEdit,
      editAvatar,
      handleFileChange,
      avatarModalVisible,
      showAvatarModal,
      goBack,
      fileInput
    }
  }
})
</script>

<style scoped>
.user-profile-card {
  max-width: 600px;
  margin: 20px auto;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.avatar-section {
  display: flex;
  align-items: center;
}
.edit-avatar-btn {
  margin-left: 10px;
}
.large-avatar {
  width: 100%;
  height: auto;
}
</style>
